/*
* ECARX Technology Limited is the owner of the copyright and the trade secret of this software. 
* Without permission, no one has the right to obtain, disclose or use this software in any way.
*/

package com.ecarx.systemui.plugin.ui.dialog.base;

import android.os.Handler;
import android.os.Looper;

/**
 * author : jack(黄冲)
 * e-mail : 907755845@qq.com
 * create : 11/16/20
 * desc   :计时器
 */
public class TimerHandler {

    private final Handler mHandler = new Handler(Looper.getMainLooper());
    private MyRunnable mRunnable;

    /**
     * author  : jack(黄冲)
     * time    : 11/16/20 6:17 PM
     * desc    : 使用 obtainTimerHandler 方式来创建
     */
    private TimerHandler() { }

    public static synchronized TimerHandler obtainTimerHandler(){
        return new TimerHandler();
    }

    /**
     * author  : jack(黄冲)
     * time    : 11/16/20 5:47 PM
     * @param surplusTimeMs 剩余时间毫秒
     * desc    : 启动计时器
     */
    public void start(long surplusTimeMs, TimerChangeListener listener){
        cancel();
        mRunnable = new MyRunnable(listener);
        mHandler.postDelayed(mRunnable, surplusTimeMs);
    }

    /**
     * author  : jack(黄冲)
     * time    : 11/16/20 6:16 PM
     * desc    : 取消计时器
     */
    public void cancel(){
        if (mRunnable != null){
            mRunnable.cancel();
            mHandler.removeCallbacks(mRunnable);
            mRunnable = null;
        }
    }


    public interface TimerChangeListener{
        /**
         * author  : jack(黄冲)
         * time    : 11/17/20 11:34 AM
         * desc    : 在取消时
         */
        void onCancel();

        /**
         * author  : jack(黄冲)
         * time    : 11/17/20 11:34 AM
         * desc    : 在完成时
         */
        void onComplete();
    }

    public abstract static class TimerCompleteListener implements TimerChangeListener{
        @Override
        public void onCancel() {

        }
    }

    private static class MyRunnable implements Runnable {
        private final TimerChangeListener mListener;

        public MyRunnable(TimerChangeListener listener) {
            mListener = listener;
        }

        @Override
        public void run() {
            mListener.onComplete();
        }

        public void cancel(){
            mListener.onCancel();
        }
    }
}
